package com.hxd.tabactivityfragment.base

import android.content.Context
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.support.v7.app.AppCompatActivity
import android.view.inputmethod.InputMethodManager
import org.jetbrains.anko.AnkoLogger
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast

/*
 *  项目名：    Tab+Activity+Fragment
 *  包名：      com.hxd.tabactivityfragment.base
 *  文件名:     BaseActivity
 *  创建者:     HXD
 *  创建时间:   2019/3/7 13:56
 *  描述:       所有Activity的基类
 */

abstract class BaseActivity : AppCompatActivity(), AnkoLogger {

    private val HANDLER by lazy { Handler(Looper.getMainLooper()) }

    /**
     * 获取一个 Handler 对象
     */
    fun getHandler(): Handler = HANDLER

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        iniActivity()

    }

    private fun iniActivity(){
        initLayout()
        initListener()
        initView()
        initData()
    }

    protected open fun initLayout() {
        if (getLayoutId() > 0) {
            setContentView(getLayoutId())
        }
    }

    //初始化数据
    protected open fun initData(){

    }

    //adapter listener
    protected open fun initListener(){

    }

    // 初始化控件
    protected open fun initView(){

    }

    // 引入布局
    abstract fun getLayoutId(): Int

    // 标题栏id
    abstract fun getTitleBarId(): Int

    override fun finish() {
        super.finish()
        hideSoftKeyboard()
    }

    /**
     * 获取一个 Context 对象
     */
    fun getContext(): Context = baseContext

    /**
     * 获取当前 Activity 对象
     */
    fun <A : BaseActivity> getActivity(): A = this as A


    /**
     * 在主线程中弹出Toast
     */
    protected fun myToast(msg:String){
        runOnUiThread{
            toast(msg)
        }
    }

    /**
     * 开启一个Activity并且finish当前界面
     */
    inline fun <reified T: BaseActivity> startActivityAndFinish(){
        startActivity<T>()
        finish()
    }

    /**
     * 隐藏软键盘
     */
    private fun hideSoftKeyboard() {
        // 隐藏软键盘，避免软键盘引发的内存泄露
        val view = currentFocus
        if (view != null) {
            val manager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            manager?.hideSoftInputFromWindow(view.windowToken, 0)
        }
    }
}